import React, { useState } from 'react'
import { Checkbox, Button, List, Space, Input, message } from 'antd'
import { CloseOutlined, EditOutlined } from '@ant-design/icons'

import './index.less'

interface IProps {
    id: string,
    text: string,
    checked: boolean,
    isEditable: boolean,
    changeCheck: Function,
    deleteItem: Function,
    editItem: Function,
    changeText: Function,
    cancelEdit: Function
}

// 列表选项
export default function TodoItem(props: IProps) {

    const { id, text, checked, isEditable, changeCheck, deleteItem, editItem, changeText, cancelEdit } = props
    const [visible, setVisible] = useState(false)

    const handleBlur = e => {
        if (!e.target.value || !e.target.value.trim()) {
            message.warning('请输入内容后再保存!')
            return
        }

        cancelEdit(id)
    }

    const handleKeyDown = e => {
        if (e.keyCode === 13) {
            let value = e.target.value.trim()
            if (!value) {
                message.warning('请输入文本后再保存!')
                return
            }
            cancelEdit(id)
        }
    }

    return (
        <List.Item onMouseEnter={() => setVisible(true)} onMouseLeave={() => setVisible(false)} style={{ padding: 20 }} className='todo-item'>
            <Space align='center' style={{ width: 350 }}>
                <Checkbox checked={checked} onChange={e => changeCheck(id, e.target.checked)} />
                {isEditable ? (
                    <Input value={text}
                        onChange={e => changeText(id, e.target.value)}
                        onKeyDown={handleKeyDown}
                        onBlur={handleBlur}
                        style={{ width: 312 }}
                    />
                ) : (
                    <p>{text}</p>
                )}
            </Space>
            {visible && (
                <Space className='extra-btns'>
                    <Button onClick={() => editItem(id)} type='link' icon={<EditOutlined />}></Button>
                    <Button onClick={() => deleteItem(id)} type='link' danger className='delete-btn' icon={<CloseOutlined />}></Button>
                </Space>
            )}
        </List.Item>
    )
}
